import csv
import logging
from logging import config

import pymysql
from faker import Faker


class DbUtils():

    def __init__(self,db):
        self.db = db


    def update(self,sql,params=[]):
        n=0
        try:
            # 1.获取连接对象
            conn = pymysql.connect(user="root", password="root", host="127.0.0.1", port=3306, database=self.db)
            # 2.获取游标对象
            curser = conn.cursor()
            # 4.执行sql
            n = curser.execute(sql,params)

        except Exception as e:
            print(e)
        else:
            # 5.提交事务
            conn.commit()
        finally:
            # 6.释放资源
            curser.close()
            conn.close()
            return n

    def selectOne(self,sql,params=[]):
        result = None
        try:
            # pymysql实现数据的查询
            conn = pymysql.connect(user="root", password="root", host="127.0.0.1", port=3306, database=self.db)
            # 获取游标对象 执行sql
            cursor = conn.cursor()
            cursor.execute(sql, params)
            result = cursor.fetchone()
            # 释放资源
        except Exception as e:
            print(e)
        finally:
            cursor.close()
            conn.close()
        return result

    def selectAll(self, sql, params=[]):
        result = None
        try:
            # pymysql实现数据的查询
            conn = pymysql.connect(user="root", password="root", host="127.0.0.1", port=3306, database=self.db)
            # 获取游标对象 执行sql
            cursor = conn.cursor()
            cursor.execute(sql, params)
            result = cursor.fetchall()
        except Exception as e:
            print(e )
        finally:
            # 释放资源
            cursor.close()
            conn.close()
        return result

    def selectMany(self, sql,n=1, params=[]):
        result = None
        try:
            # pymysql实现数据的查询
            conn = pymysql.connect(user="root", password="root", host="127.0.0.1", port=3306, database=self.db)
            # 获取游标对象 执行sql
            cursor = conn.cursor()
            cursor.execute(sql, params)
            result = cursor.fetchmany(n)
        except Exception as e:
            print(e)
        finally:
            # 释放资源
            cursor.close()
            conn.close()
        return result

# 定义faker变量
faker = Faker("zh_cn")

def getLogger():
    # 加载配置文件
    config.fileConfig("conf/log.conf")
    # 获取日志对象
    logger = logging.getLogger()
    return logger


def getCsvData(path):
    # 读取文件
    csvFile = open(path, mode="r", encoding="utf-8")
    # 使用csv模块读取文件
    reader = csv.reader(csvFile)
    # 遍历数据
    dataList = []
    for r in reader:
        dataList.append(r)

    csvFile.close()

    return dataList


baseUrl = "http://127.0.0.1:6688"